package controllers

import (
	"encoding/json"
	"weiboxs.com/new_h_glasses/enums"
	"weiboxs.com/new_h_glasses/models"
	"weiboxs.com/new_h_glasses/utils"
)

type InspectsController struct {
	BaseController
}

func (c *InspectsController) Index() {
	c.checkAuthor("inspects/index")
	if c.Ctx.Input.IsPost() {
		var qs models.InspectsQueryParam
		json.Unmarshal(c.Ctx.Input.RequestBody, &qs)
		data, count := models.InspectsPageList(&qs)
		c.jsonDataTable(count, data)
	}
	c.Data["activeSidebarUrl"] = "/inspects/index"
	c.display("", "inspects/index_footerjs.html")
}

//停启用
func (c *InspectsController) Delete() {
	if c.Ctx.Input.IsPost() {
		c.checkAuthor("inspects/index")
		inspects_id, _ := c.GetInt64("inspects_id")
		if inspects_id == 0 {
			c.jsonResult(enums.JRCodeFailed, "参数错误", "")
		}
		if err := models.InspectsDeleteById(inspects_id); err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		}
		c.jsonResult(enums.JRCodeSucc, "ok", "")
	}
}

//新增/编辑
func (c *InspectsController) Edit() {
	c.checkAuthor("inspects/index")
	id, _ := c.GetInt64(":id")

	m := new(models.Inspects)
	if c.Ctx.Input.IsPost() {
		m := models.Inspects{}

		if err := c.ParseForm(&m); err != nil {
			c.jsonResult(enums.JRCodeFailed, "提交参数错误", "")
		}
		m.Department = &models.Department{Id: c.curUser.DepartmentId}
		m.CreatedBy = c.curUser.RealName
		m.UpdatedBy = c.curUser.RealName
		m.Pinyin = utils.ConvertPinyin(m.ProductName)

		if m.Id == 0 { //新增
			if _, err := models.InspectsAdd(&m); err != nil {
				c.jsonResult(enums.JRCodeFailed, "新增失败:"+err.Error(), "")
			} else {
				c.jsonResult(enums.JRCodeSucc, "新增成功", "")
			}
		} else { //修改
			if _, err := models.InspectsEdit(&m); err != nil {
				c.jsonResult(enums.JRCodeFailed, "修改失败:"+err.Error(), "")
			} else {
				c.jsonResult(enums.JRCodeSucc, "修改成功", "")
			}
		}
	} else {

		m.Id = id
		if id > 0 {
			m = models.InspectsFindOne(id)
			if m.Id == 0 {
				c.pageError("找不到信息")
			}
		}
		c.Data["m"] = m

		c.display("", "inspects/edit_footerjs.html", "shared/layout_dialog.html")
	}
}

//项目调价
func (c *InspectsController) EditPrice() {
	c.checkAuthor("inspects/index")
	inspects_id, _ := c.GetInt64(":id")
	if inspects_id == 0 {
		c.pageError("参数错误")
	}
	if c.Ctx.Input.IsPost() {
		new_price, _ := c.GetFloat("new_price")
		if err := models.InspectsEditPrice(inspects_id, new_price, c.curUser.RealName); err != nil {
			c.jsonResult(enums.JRCodeFailed, "调价失败:"+err.Error(), "")
		} else {
			c.jsonResult(enums.JRCodeSucc, "调价成功", "")
		}
	}
	c.Data["m"] = models.InspectsFindOne(inspects_id)
	c.display("", "inspects/editprice_footerjs.html", "shared/layout_dialog.html")
}

//调价明细
func (c *InspectsController) EditPriceRecord() {
	var qs models.InspectsPriceLogQueryParam
	json.Unmarshal(c.Ctx.Input.RequestBody, &qs)
	data, count := models.InspectsPriceLogPageList(&qs)
	c.jsonDataTable(count, data)
}
